const koa = require('koa');
let app = new koa();

// 1. 引入中间件
const assets = require('koa-static');


// 2. 配置中间件
app.use(assets('uploads')); // 指定静态文件存放目录
// 允许跨域
var cors = require('koa2-cors');
app.use(cors({
 origin: '*'
}));

const koaBody = require('koa-body');
app.use(koaBody(
    {
        multipart: true,
    }
))
const jwt = require('jsonwebtoken')
// 登录拦截
app.use(async function (ctx, next) {
    let notCheck = [
        '/login','/register','/add/category','/files'
    ]
    if (notCheck.includes(ctx.path)) {
        // console.log(111);
        await next()
    } else {
        // token 不存在的情况
        if (!ctx.headers.token) { 
            ctx.status = 401
            return ctx.body = '未登录'
        }
        try {
            let info = jwt.verify(ctx.headers.token, 'dgfshjdsjhgdhbas');
            ctx.user = info
            // 验证通过后，触发下一个中间件
            await next()
        } catch (error) {
            console.log(error); 
            ctx.status = 401
            return ctx.body = '未登录' 
        }
    }
})

const admin = require('./router/adminRouter.js');
const user = require('./router/userRouter.js');
const category = require('./router/categoryRouter.js');

 
app.use(admin.routes()).use(admin.allowedMethods());
app.use(user.routes()).use(user.allowedMethods());
app.use(category.routes()).use(category.allowedMethods());

const picture =require('./router/pictureRouter.js');

app.use(picture.routes()).use(picture.allowedMethods())


app.listen(8001, () => {
    console.log('服务端启动成功8001')
})